import pandas as pd
import Core.Gadget as Gadget
import Core.MongoDB as MongoDB
import datetime


def StockList(database, datetime2):
    trades = database.find("Instruments", "Stock")
    symbols = []
    for trade in trades:
        if trade["DateTime2"]< datetime2:
            continue
        symbol = trade["Symbol"]
        symbols.append(symbol)
    return symbols

def MaxRetracement(timeserise):
    # 读取sheet1中的内容，存放在data中，数据类型为DataFrame
    df = pd.DataFrame(timeserise, columns=['closeprice'])
    Max = df.max()
    Min = df.min()
    drawback = (Max - Min) / Max
    a = list(drawback)
    b = list(Min)
    drawback = a[0]
    Min = b[0]
    return(drawback, Min)

def screening_condition_quotes(stock_list, datetime1, datetime2, min_fall = 0.9):
    for i in range(len(stock_list)):
        symbol = stock_list[i]
        quotes = database.find("Quote", symbol + "_Time_86400_Bar", datetime1, datetime2)
        quote = quotes[-1]
        prices = []
        for i in range(len(quotes)):
            prices.append(quotes[i]["Close"]/quotes[i]["AdjFactor"])
        Maxretracement = MaxRetracement(prices)
        if Maxretracement[0] > min_fall and Maxretracement[1] == quote["Close"]:  # 最高点跌幅首超90%
            print(symbol, quote["Close"],Maxretracement[0])



from Core.Config import Config
config = Config()
database = config.DataBase()
datetime1 = datetime.datetime(1998, 5, 2)
datetime1 = Gadget.ToUTCDateTime(datetime1)
datetime2 = datetime.datetime(2018, 10, 23)
datetime2 = Gadget.ToUTCDateTime(datetime2)

stock_list = StockList(database,datetime2)
stock_list_1 = screening_condition_quotes(stock_list,datetime1,datetime2, min_fall = 0.95)
